package org.ant.ctrl;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.ant.gui.panes.InputTabbedPane;
import org.ant.util.Code;

public class CodesManager implements ChangeListener {
	public static CodesManager codesManager;

	public static final String INF_CHANGETAB = "CHANGE TAB";
	public static final String INF_COMPILE = "COMPILE";
	public static final String INF_NEW = "NEW";
	public static final String INF_OPEN = "OPEN";

	public static CodesManager getInstane() {
		if (codesManager == null) {
			codesManager = new CodesManager();
			//codesManager.newCode();
		}
		return codesManager;
	}

	private ArrayList<Code> codes;
	private ArrayList<ActionListener> actionListeners;
	private int current;

	private CodesManager() {
		codes = new ArrayList<Code>();
		actionListeners = new ArrayList<ActionListener>();
		current = -1;
	}

	public void newCode() {
		Code code = new Code(null);
		codes.add(code);
		current = codes.size() - 1;
		broadCasting(INF_NEW);
	}

	public void openCode(String path) {
		boolean flag = true;
		for (Code code : codes) {
			if (path.equals(code.getPath())) {
				flag = false;
			}
		}
		if (flag) {
			codes.add(new Code(path));
			current = codes.size() - 1;
		}
		broadCasting(INF_OPEN);
	}

	public void deleteCurrentCode(){
		codes.remove(current);
		//broadCasting(INF_OPEN);
	}
	
	public boolean saveCode() {
		return false;
	}

	public void compile() {
		if (codes.size() > 0) {
			codes.get(0).compile();
		}
		broadCasting(INF_COMPILE);
	}

	public Code getCode(int i) {
		return codes.get(i);
	}

	public Code getCurrentCode() {
		if (current >= 0) {
			return codes.get(getCurrent());
		}
		return null;
	}

	public int getCodesSize() {
		return codes.size();
	}

	public int getCurrent() {
		return current;
	}

	public void setCurrent(int current) {
		this.current = current;
	}

	public void addActionListener(ActionListener actionListener) {
		if (!actionListeners.contains(actionListener)) {
			actionListeners.add(actionListener);
		}
	}

	public void broadCasting(String inf) {
		System.err.println("CodeManager: " + inf);
		ActionEvent event = new ActionEvent(this, 0, inf);
		for (ActionListener listener : actionListeners) {
			listener.actionPerformed(event);
		}
	}

	@Override
	public void stateChanged(ChangeEvent e) {
		if (e.getSource() instanceof InputTabbedPane) {
			InputTabbedPane itPane = (InputTabbedPane) e.getSource();
			current = itPane.getSelectedIndex();
			broadCasting(INF_CHANGETAB);
		}
	}
}
